package com.arunsawad.ilertu.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.ILertU;
import com.arunsawad.ilertu.common.LoadImageTask;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Utils;
import com.arunsawad.ilertu.common.Validator;

public class EditProfile extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	AlertDialog.Builder alertDialogBuilder;
	static final int DATE_DIALOG_ID = 0;
	private int mYear;
	private int mMonth;
	private int mDay;
	private static final int TAKE_PICTURE = 1; // flag
	private static final int SELECT_PICTURE = 2; // flag
	private static final int GET_PROFILE = 3; // flag
	private static final int UPDATE_PROFILE = 4; // flag
	int currentAction;
	EditText txtBirthday;
	ImageView imgProfile;
	AlertDialog alert;
	String imgBase64;
	String currentProfileImage = "";
	Spinner spinnerGender;
	String gender;
	ProgressDialog bar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set custom title
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_editprofile);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title0_imgbtn_txt);
		initTitle();

		// init preferences
		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);

		// show loading bar
		bar = new ProgressDialog(EditProfile.this);
		bar.setIndeterminate(true);
		bar.show();

		// check login
		Validator.Validate(this, preferences);

		txtBirthday = (EditText) findViewById(R.id.editprofile_txtBirthday);
		imgProfile = (ImageView) findViewById(R.id.editprofile_imageViewPhoto);
		spinnerGender = (Spinner) findViewById(R.id.editprofile_spinnerGender);

		String path = ((ILertU) this.getApplication()).getImagePath();
		if (path.equals("")) {
			// get profile
			getProfile();
		} else {
			// set user image if taken
			File imgFile = new File(path);
			if (imgFile.exists()) {
				Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
						.getAbsolutePath());
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

				byte[] b = bytes.toByteArray();
				imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

				imgProfile.setImageBitmap(myBitmap);
			}
			bar.hide();
		}

		// calendar listener
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		txtBirthday.setText("Birthday (dd/mm/yyyy)");
		txtBirthday.setOnTouchListener(new OnTouchListener() {
			@SuppressWarnings("deprecation")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(DATE_DIALOG_ID);
				return false;
			}
		});

		// gender listener
		spinnerGender
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						gender = parent.getItemAtPosition(pos).toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
	}

	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title0_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title0_txtTitle);
		txtTitle.setText(getString(R.string.edit_profile));
	}

	public void getProfile() {
		String msg = String.format(Constants.MSG, "ilertu.user-get",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), "");

		currentAction = GET_PROFILE; // flag
		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_GET_PROFILE, msg);
	}

	// {{ onClick events
	public void changeImage(View view) {
		alertDialogBuilder = new Builder(EditProfile.this);
		alertDialogBuilder.setTitle(getString(R.string.photo_options));
		String[] types = { getString(R.string.take_photo),
				getString(R.string.image_from_gallery) };
		alertDialogBuilder.setItems(types,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							Intent intent = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(intent, TAKE_PICTURE);
							break;
						case 1:
							Intent photoPickerIntent = new Intent();
							photoPickerIntent.setType("image/*");
							photoPickerIntent
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(photoPickerIntent,
									SELECT_PICTURE);
							break;
						default:
							break;
						}
					}
				});
		alertDialogBuilder.show();
	}

	public void update(View view) {
		String filter = "";
		filter += "	<user id=\""
				+ preferences.getString(Constants.PREF_USER_ID, "") + "\">";
		filter += "		<idCard>"
				+ ((EditText) findViewById(R.id.editprofile_txtIdCard))
						.getText() + "</idCard>";
		filter += "		<name>";
		filter += "			<given>"
				+ ((EditText) findViewById(R.id.editprofile_txtFirstName))
						.getText() + "</given>";
		filter += "			<family>"
				+ ((EditText) findViewById(R.id.editprofile_txtLastName))
						.getText() + "</family>";
		filter += "		</name>";
		filter += "		<gender>" + gender + "</gender>";
		filter += "		<phone>"
				+ ((EditText) findViewById(R.id.editprofile_txtMobileNo))
						.getText() + "</phone>";
		filter += "		<birthday>"
				+ ((EditText) findViewById(R.id.editprofile_txtBirthday))
						.getText() + "</birthday>";
		if (imgBase64 != null && !imgBase64.equals("")) {
			filter += "		<image>";
			filter += "			<imageSource>" + imgBase64 + "</imageSource>";
			filter += "			<postType>2</postType>";
			filter += "		</image>";
		} else {
			filter += "		<image/>";
		}
		filter += "	</user>";

		String msg = String.format(Constants.MSG, "ilertu.user-update",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), filter);

		currentAction = UPDATE_PROFILE;
		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_UPDATE_PROFILE, msg);
	}

	// }}

	// {{ callback
	// taking/selecting picture
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String imagePath = "";
		Bitmap photo = null;
		if (requestCode == TAKE_PICTURE) {
			if (data != null) {
				photo = (Bitmap) data.getExtras().get("data");
			}
		} else {
			if (requestCode == SELECT_PICTURE) {
				Uri uri = data.getData();
				String path = Utils.getPathFromURI(this, uri);
				int orientation = Utils.getImageAngle(this, uri);
				photo = Utils.getImageFromPath(this, path, orientation);
			}
		}
		photo = Utils.resizeImage(photo, Constants.USER_IMAGE_WIDTH,
				Constants.USER_IMAGE_HEIGHT);
		try {
			imagePath = Environment.getExternalStorageDirectory()
					+ File.separator + Constants.TEMP_IMAGE;
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

			byte[] b = bytes.toByteArray();
			imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

			File f = new File(imagePath);
			if (f.exists()) {
				f.delete();
			}

			// write the bytes in file
			FileOutputStream fo = new FileOutputStream(imagePath);
			fo.write(bytes.toByteArray());

			fo.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		imgProfile.setImageBitmap(photo);

		((ILertU) this.getApplication()).setImagePath(imagePath);
	}

	// {{ date picker
	@Override
	protected Dialog onCreateDialog(int id) {
		return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private void updateDisplay() {
		txtBirthday.setText(new StringBuilder().append(padZero(mDay))
				.append("/").append(padZero(mMonth + 1)).append("/")
				.append(mYear));
		// Month is 0 based
	}

	public String padZero(int value) {
		if (String.valueOf(value).length() == 1)
			return "0" + String.valueOf(value);
		else
			return String.valueOf(value);
	}

	// }}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			if (currentAction == GET_PROFILE || currentAction == UPDATE_PROFILE) {
				DocumentBuilderFactory factory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder builder;
				try {
					builder = factory.newDocumentBuilder();
					Document document = builder.parse(new InputSource(
							new StringReader(results)));

					NodeList listOfItems = document
							.getElementsByTagName("user");
					int totalElements = listOfItems.getLength();

					if (totalElements > 0) {
						if (currentAction == GET_PROFILE) {
							Element user = (Element) listOfItems.item(0);
							String birthday = "";
							try {
								birthday = user
										.getElementsByTagName("birthday")
										.item(0).getTextContent();
							} catch (Exception ex) {
							}
							txtBirthday.setText(birthday);

							try {
								imgProfile.setTag(user
										.getElementsByTagName("imageUrl")
										.item(0).getTextContent());
								LoadImageTask loadImageTask = new LoadImageTask();
								loadImageTask.execute(imgProfile);
							} catch (Exception ex) {
							}

							((EditText) findViewById(R.id.editprofile_txtFirstName))
									.setText(user.getElementsByTagName("given")
											.item(0).getTextContent());
							((EditText) findViewById(R.id.editprofile_txtLastName))
									.setText(user
											.getElementsByTagName("family")
											.item(0).getTextContent());
							((EditText) findViewById(R.id.editprofile_txtIdCard))
									.setText(user
											.getElementsByTagName("idCard")
											.item(0).getTextContent());
							((EditText) findViewById(R.id.editprofile_txtMobileNo))
									.setText(user.getElementsByTagName("phone")
											.item(0).getTextContent());

							String[] genders = getResources().getStringArray(
									R.array.genders);
							int genderPosition = 0;
							String gender = user.getElementsByTagName("gender")
									.item(0).getTextContent();
							for (int i = 0; i < genders.length; i++) {
								if (genders[i].equals(gender)) {
									genderPosition = i;
									break;
								}
							}
							spinnerGender.setSelection(genderPosition);
							bar.hide();
						} else {
							alertDialogBuilder = new AlertDialog.Builder(this);
							alertDialogBuilder
									.setMessage(R.string.profile_updated)
									.setCancelable(false)
									.setPositiveButton(
											R.string.ok,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													Intent intent = new Intent(
															EditProfile.this,
															Index.class);
													startActivity(intent);
												}
											});
							alert = alertDialogBuilder.create();
							alert.show();
						}
					} else {
						listOfItems = document.getElementsByTagName("error");
						totalElements = listOfItems.getLength();
						if (totalElements > 0) {
							Element error = (Element) listOfItems.item(0);
							String message = error
									.getElementsByTagName("errorDesc").item(0)
									.getTextContent();
							Utils.alert(this, message);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	// }}
}